package com.fooddiary.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;

import com.fooddiary.util.ApplicationUtils;

/**
 * Abstract class for controllers. Contain common properties and methods <br>
 * @author Created by andrey.kuznetsov <br>
 * @author Last modified by $Author$ <br>
 * @author Last modified on $Date$ at revision $Revision$ <br>
 */
public abstract class AbstractController{
	
	protected Logger log = Logger.getLogger(getClass());
	
	protected final String ERROR_URL="/public/error";
	
	/*general keys for json data */
	public static final String KEY_DATA = "data";
	public static final String KEY_TOTAL = "total";
	public static final String KEY_ID = "id";
	public static final String KEY_SUCCESS = "success";
	public static final String KEY_MESSAGE = "message";
	
	@Autowired 
	protected MessageSource messageSource;
	
	@Autowired
	protected ApplicationUtils applicationUtils;
	
	/**
	 * Pack received data for responce map <br>
	 * @param p_objects - list of objects for responce; {@link List}<?> <br>
	 * @return {@link Map}<{@link String}, {@link Object}}>
	 */
	protected Map<String,Object> getMap(List <?> p_objects){	
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put(KEY_TOTAL, p_objects.size());
		modelMap.put(KEY_DATA, p_objects);
		modelMap.put(KEY_SUCCESS, true);
		return modelMap;
	}

	/**
	 * Pack received data for responce map <br>
	 * @param p_objects - array of objects where: <br>
	 * Object[0] - list of objects for responce; {@link List}<?> <br>
	 * Object[0] - total count of objects for pagination; {@link Long}<?> <br>
	 * @return {@link Map}<{@link String}, {@link Object}}>
	 */
	protected Map<String,Object> getMap(Object[] p_objects){	
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put(KEY_TOTAL, p_objects[1]);
		modelMap.put(KEY_DATA, p_objects[0]);
		modelMap.put(KEY_SUCCESS, true);
		return modelMap;
	}
	
	/**
	 * Pack received data with single object for response <br>
	 * @param p_object - objcet for responce; {@link Object} <br>
	 * @return {@link Map}<{@link String}, {@link Object}}>
	 */
	protected Map<String,Object> getMap(Object p_object){	
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put(KEY_DATA, p_object);
		modelMap.put(KEY_SUCCESS, true);
		return modelMap;
	}
	
	/**
	 * Pack received data with error message <br>
	 * @param p_msg - error message; {@link String} <br>
	 * @return {@link Map}<{@link String}, {@link Object}}>
	 */
	protected Map<String,Object> getModelMapError(String p_msg){
		Map<String,Object> modelMap = new HashMap<String,Object>(2);
		modelMap.put(KEY_MESSAGE, p_msg);
		modelMap.put(KEY_SUCCESS, false);
		return modelMap;
	}

}
